#include "gamescene.h"
#include "player.h"
#include "house.h"
#include "bullet.h"
#include "zombie.h"
#include <QGraphicsPixmapItem>
#include <QFont>
#include <QGraphicsProxyWidget>
#include <QDebug>

/**
 * @brief GameScene 构造函数
 */
GameScene::GameScene(QObject *parent)
    : QGraphicsScene(parent),
    m_player(nullptr),
    m_house(nullptr),
    m_score(0),
    m_sunshine(100)
{
    // --- 调试 --- 打印场景尺寸信息
    qDebug() << "[构造函数] GameScene 构造函数被调用。";

    // **重要修改：从这里移除 initScene() 的调用**

    // 连接并启动游戏主循环定时器
    connect(&m_gameTimer, &QTimer::timeout, this, &GameScene::gameLoop);
    m_gameTimer.start(16);

    // 连接并启动僵尸生成定时器
    connect(&m_zombieSpawnTimer, &QTimer::timeout, this, &GameScene::spawnZombie);
    m_zombieSpawnTimer.start(3000);
}

/**
 * @brief GameScene 析构函数
 */
GameScene::~GameScene()
{
}

/**
 * @brief 初始化场景，设置背景，添加玩家、房子和UI元素
 */
void GameScene::initScene()
{
    qDebug() << "[initScene] initScene() 函数开始执行。";
    qDebug() << "[initScene] 当前场景尺寸:" << sceneRect(); // 此时应该有正确尺寸了

    // 1. 设置场景背景
    setBackgroundBrush(QPixmap(":/assets/background.jpg"));

    // 2. 创建并添加房子
    m_house = new House();

    QPointF sceneCenter = sceneRect().center();
    qreal houseWidth = m_house->boundingRect().width();
    qreal houseHeight = m_house->boundingRect().height();
    QPointF housePos(sceneCenter.x() - houseWidth / 2, sceneCenter.y() - houseHeight / 2);

    qDebug() << "[initScene] 场景中心点:" << sceneCenter;
    qDebug() << "[initScene] 房子尺寸 (宽x高):" << houseWidth << "x" << houseHeight;
    qDebug() << "[initScene] 计算出的房子左上角坐标:" << housePos;

    m_house->setPos(housePos);
    m_house->setZValue(0);
    addItem(m_house);

    // 3. 创建并添加玩家
    m_player = new Player();
    m_player->setPos(m_house->pos().x() + 50, m_house->pos().y() + 150);
    m_player->setZValue(2);
    addItem(m_player);
    m_player->setFocus();

    // 4. 创建并添加UI文本项
    QFont uiFont("Arial", 16, QFont::Bold);
    m_scoreText = new QGraphicsTextItem();
    m_scoreText->setFont(uiFont);
    m_scoreText->setDefaultTextColor(Qt::white);
    m_scoreText->setPos(10, 10);
    m_scoreText->setZValue(10);
    addItem(m_scoreText);

    m_sunshineText = new QGraphicsTextItem();
    m_sunshineText->setFont(uiFont);
    m_sunshineText->setDefaultTextColor(Qt::yellow);
    m_sunshineText->setPos(10, 40);
    m_sunshineText->setZValue(10);
    addItem(m_sunshineText);

    m_houseHealthText = new QGraphicsTextItem();
    m_houseHealthText->setFont(uiFont);
    m_houseHealthText->setDefaultTextColor(Qt::red);
    m_houseHealthText->setPos(sceneRect().width() - 200, 10);
    m_houseHealthText->setZValue(10);
    addItem(m_houseHealthText);

    updateUI();
    qDebug() << "[initScene] initScene() 函数执行完毕。";
}

// ... gameLoop() 及之后的所有函数保持不变 ...
/**
 * @brief 游戏主循环，每一帧都被调用
 */
void GameScene::gameLoop()
{
    m_player->move(m_keysPressed);
    m_player->setRotationToMouse(m_mousePos);

    for (QGraphicsItem *item : items()) {
        if (Bullet *bullet = dynamic_cast<Bullet*>(item)) {
            bullet->move();
            // --- 调试 --- 每一帧都打印子弹的位置
            // qDebug() << "[gameLoop] 子弹当前位置:" << bullet->pos();

            if (!sceneRect().intersects(bullet->boundingRect())) {
                qDebug() << "[gameLoop] 子弹飞出屏幕，准备销毁。位置:" << bullet->pos();
                removeItem(bullet);
                delete bullet;
            }
        } else if (Zombie *zombie = dynamic_cast<Zombie*>(item)) {
            zombie->moveTowards(m_house->pos());
        }
    }

    checkCollisions();
    updateUI();
}

/**
 * @brief 定时生成僵尸
 */
void GameScene::spawnZombie()
{
    Zombie *zombie = new Zombie();
    int side = rand() % 4;
    qreal x=0, y=0;
    switch(side) {
    case 0: x = rand() % (int)sceneRect().width(); y = -zombie->boundingRect().height(); break;
    case 1: x = rand() % (int)sceneRect().width(); y = sceneRect().height(); break;
    case 2: x = -zombie->boundingRect().width(); y = rand() % (int)sceneRect().height(); break;
    case 3: x = sceneRect().width(); y = rand() % (int)sceneRect().height(); break;
    }
    zombie->setPos(x, y);
    zombie->setZValue(1); // 僵尸在房子上，在玩家下
    addItem(zombie);
}

/**
 * @brief 碰撞检测
 */
void GameScene::checkCollisions()
{
    QList<QGraphicsItem*> allItems = items();
    for (QGraphicsItem *itemA : allItems) {
        Zombie *zombie = dynamic_cast<Zombie*>(itemA);
        if (!zombie) continue;

        QList<QGraphicsItem*> colliding_items = zombie->collidingItems();
        for (QGraphicsItem *itemB : colliding_items) {
            if (Bullet *bullet = dynamic_cast<Bullet*>(itemB)) {
                zombie->takeDamage(bullet->damage());
                removeItem(bullet);
                delete bullet;
                if (zombie->health() <= 0) {
                    m_score += 10;
                    m_sunshine += 5;
                    removeItem(zombie);
                    delete zombie;
                    goto next_zombie;
                }
            } else if (House *house = dynamic_cast<House*>(itemB)) {
                house->takeDamage(zombie->damage());
                removeItem(zombie);
                delete zombie;
                if (house->health() <= 0) {
                    gameOver();
                    return;
                }
                goto next_zombie;
            }
        }
    next_zombie:;
    }
}

/**
 * @brief 更新UI显示
 */
void GameScene::updateUI()
{
    m_scoreText->setPlainText("分数: " + QString::number(m_score));
    m_sunshineText->setPlainText("阳光: " + QString::number(m_sunshine));
    m_houseHealthText->setPlainText("房子生命: " + QString::number(m_house->health()));
}

/**
 * @brief 游戏结束处理
 */
void GameScene::gameOver()
{
    m_gameTimer.stop();
    m_zombieSpawnTimer.stop();
    QGraphicsRectItem* panel = new QGraphicsRectItem(sceneRect());
    panel->setBrush(QColor(0, 0, 0, 150));
    panel->setZValue(9);
    addItem(panel);
    QGraphicsTextItem* gameOverText = new QGraphicsTextItem("游戏结束");
    QFont font("Arial", 50, QFont::Bold);
    gameOverText->setFont(font);
    gameOverText->setDefaultTextColor(Qt::white);
    gameOverText->setPos(sceneRect().center().x() - gameOverText->boundingRect().width()/2,
                         sceneRect().center().y() - gameOverText->boundingRect().height()/2);
    gameOverText->setZValue(10);
    addItem(gameOverText);
}

void GameScene::keyPressEvent(QKeyEvent *event)
{
    if (!event->isAutoRepeat()) m_keysPressed[event->key()] = true;
    QGraphicsScene::keyPressEvent(event);
}

void GameScene::keyReleaseEvent(QKeyEvent *event)
{
    if (!event->isAutoRepeat()) m_keysPressed[event->key()] = false;
    QGraphicsScene::keyReleaseEvent(event);
}

void GameScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
    m_mousePos = event->scenePos();
    QGraphicsScene::mouseMoveEvent(event);
}

void GameScene::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        qDebug() << "\n--- [点击事件] ---";
        qDebug() << "[点击事件] 鼠标左键按下。鼠标场景坐标:" << m_mousePos;
        qDebug() << "[点击事件] 玩家当前坐标:" << m_player->pos();

        Bullet *bullet = new Bullet();

        QPointF playerCenter = m_player->pos() + QPointF(m_player->boundingRect().width() / 2, m_player->boundingRect().height() / 2);
        bullet->setPos(playerCenter);
        qDebug() << "[点击事件] 计算出的玩家中心点:" << playerCenter;
        qDebug() << "[点击事件] 子弹初始位置已设置为:" << bullet->pos();

        QLineF line(playerCenter, m_mousePos);
        line.setLength(bullet->speed());
        bullet->setDirection(QPointF(line.dx(), line.dy()));
        qDebug() << "[点击事件] 子弹方向向量 (dx, dy):" << line.dx() << "," << line.dy();

        bullet->setZValue(3); // 子弹(3) > 玩家(2)
        addItem(bullet);
        qDebug() << "[点击事件] 子弹已添加到场景中。Z值:" << bullet->zValue();
        qDebug() << "--- [点击事件结束] ---\n";
    }
    QGraphicsScene::mousePressEvent(event);
}
